import React, { createContext, useState, useEffect } from 'react';
import api from '../services/api';

export const AuthContext = createContext();

export const AuthProvider = ({ children }) => {
  const [user, setUser] = useState(null);
  const [token, setToken] = useState(localStorage.getItem('token'));
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    // 如果有token，尝试加载用户信息
    const loadUser = async () => {
      if (token) {
        api.defaults.headers.common['Authorization'] = `Bearer ${token}`;
        try {
          const res = await api.get('/api/users/me');
          setUser(res.data);
        } catch (err) {
          console.error('加载用户信息失败', err);
          localStorage.removeItem('token');
          setToken(null);
          setUser(null);
          delete api.defaults.headers.common['Authorization'];
        }
      }
      setIsLoading(false);
    };

    loadUser();
  }, [token]);

  // 登录函数
  const login = async (usernameOrEmail, password) => {
    setError(null);
    try {
      const res = await api.post('/api/auth/signin', { usernameOrEmail, password });
      const { token: authToken, ...userData } = res.data;
      setToken(authToken);
      setUser(userData);
      localStorage.setItem('token', authToken);
      api.defaults.headers.common['Authorization'] = `Bearer ${authToken}`;
      return true;
    } catch (err) {
      console.error('登录失败', err);
      setError(err.response?.data?.message || '登录失败，请检查您的凭据');
      return false;
    }
  };

  // 注册函数
  const register = async (username, email, password) => {
    setError(null);
    try {
      await api.post('/api/auth/signup', { username, email, password });
      return true;
    } catch (err) {
      console.error('注册失败', err);
      setError(err.response?.data?.message || '注册失败，请稍后再试');
      return false;
    }
  };

  // 登出函数
  const logout = () => {
    localStorage.removeItem('token');
    setToken(null);
    setUser(null);
    delete api.defaults.headers.common['Authorization'];
  };

  // 更新用户信息
  const updateUserInfo = async (userData) => {
    setError(null);
    try {
      const res = await api.put('/api/users/me', userData);
      setUser({ ...user, ...userData });
      return true;
    } catch (err) {
      console.error('更新用户信息失败', err);
      setError(err.response?.data?.message || '更新用户信息失败');
      return false;
    }
  };

  return (
    <AuthContext.Provider
      value={{
        user,
        token,
        isLoading,
        error,
        login,
        register,
        logout,
        updateUserInfo,
        isAuthenticated: !!token,
        isAdmin: user?.roles?.includes('ROLE_ADMIN'),
      }}
    >
      {children}
    </AuthContext.Provider>
  );
};

export default AuthContext; 